import { Injectable, HttpException, HttpStatus, Inject } from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
// import { UpdateAuthDto } from './dto/update-auth.dto';
import { JwtService } from '@nestjs/jwt';
import { UserService } from 'src/user/user.service';
import { RoleService } from '../role/role.service';
import encry from '../utils/crypto';
import { User } from '../user/entities/user.entity';
import { CacheService } from 'src/cache/cache.service';
import { JWT_User } from './dto/update-auth.dto';
// import { ApiException } from '../common/filter/http-exception/api.exception';
// import { ApiErrorCode } from '../common/enums/api-error-code.enum';

@Injectable()
export class AuthService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly userService: UserService,
    private readonly roleService: RoleService,
    @Inject('REFRESH_JWT_SERVICE')
    private readonly refreshJwtService: JwtService, // RefreshToken服务
    private readonly cacheService: CacheService,
  ) {}

  async login(loginAuthDto: CreateAuthDto) {
    // throw new ApiException('啊离开家了，回家吧', ApiErrorCode.USER_NOTEXIST);
    const { userName, password } = loginAuthDto;

    const user = await this.userService.findOne(userName);
    if (user?.password !== encry(password, user.salt)) {
      throw new HttpException('密码错误', HttpStatus.UNAUTHORIZED);
    }
    // 获取拥有的按钮权限
    // const buttons = await this.userService.findPermissionNames(user);
    const refreshToken = this.generateRefreshToken(user.id.toString());
    await this.userService.updateRefreshToken(user.id, refreshToken);
    // await this.cacheService.set(
    //   `${user.id}-token`,
    //   refreshToken,
    //   60 * 60 * 24 * 7,
    // ); // 设置缓存 7天 刷新token
    // // 设置缓存 7天 角色权限
    // await this.cacheService.set(
    //   `${refreshToken}-roles`,
    //   user.roles.map((role) => role.name),
    //   60 * 60 * 24 * 7,
    // ); // 设置缓存
    // await this.cacheService.set(
    //   `${refreshToken}-buttons`,
    //   buttons,
    //   60 * 60 * 24 * 7,
    // );
    return {
      refreshToken,
      token: this.generateAccessToken({
        userId: user.id.toString(),
        username: user.username,
        roleIds: user.roles.map((role) => role.id),
        nickname: user.nickname,
      }),
    };
  }

  // 生成AccessToken
  generateAccessToken(value: {
    userId: string;
    username: string;
    roleIds: number[];
    nickname: string;
  }) {
    return this.jwtService.sign({
      sub: value.userId,
      username: value.username,
      roleIds: value.roleIds,
      nickname: value.nickname,
    });
  }

  // 生成RefreshToken
  generateRefreshToken(userId: string) {
    return this.refreshJwtService.sign({ sub: userId });
  }

  // 刷新令牌
  async refreshTokens(user: User) {
    // const userFromDb = await this.userService.findById(user.id);
    // if (!userFromDb || userFromDb.refreshToken !== refreshToken) {
    //   throw new HttpException('密码错误', HttpStatus.UNAUTHORIZED);
    // }
    const refToken = this.generateRefreshToken(user.id.toString());
    await this.userService.updateRefreshToken(user.id, refToken);
    return {
      refreshToken: refToken,
      token: this.generateAccessToken({
        userId: user.id.toString(),
        username: user.username,
        roleIds: user.roles.map((role) => role.id),
        nickname: user.nickname,
      }),
    };
  }
  // 用户身份信息
  async getUserInfo(user: JWT_User) {
    const buttons = await this.userService.findPermissionNames(user);
    const roles = await this.roleService.findUserRoles(user.roleIds);
    return {
      buttons,
      roles,
      userId: user.sub,
      userName: user.nickname,
    };
  }
}
